<!--  -->
<template style="background: red">
  <div style="display: flex;width: 100%;">
      <el-form ref="form" :model="form" :rules="rules" label-width="150px" style="margin: auto;background: blanchedalmond;width:500px;height:500px">
        <el-form-item label="月份" prop="num">
          <el-input v-model="form.num"></el-input>
        </el-form-item>
        <el-form-item label="文件:" prop="fileList">
          <el-upload align="left" :drag="true" class="upload-demo" :auto-upload="false" action=""
            :on-change="handleChange" :on-remove="handleRemove" multiple>
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">只能上传pdf文件</div>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="loading">保存</el-button>
        </el-form-item>
      </el-form>
  </div>
</template>

<script>
import rules from "@/utils/validate.js";
import { upload } from "@/api/login/index.js";
import message from "element-ui";
export default {
  data() {
    return {
      loading: false,
      form: {
        fileList: [],
        num: "",
      },
      //校验规则
      rules: rules.common,
    };
  },

  components: {},

  computed: {},

  methods: {
    /*
      上传文件请求
    */
    async uploadFile() {
      let formData = new FormData();
      formData.append("num", this.form.num);
      this.form.fileList.forEach((file) => {
        formData.append("file", file.raw);
      });
      this.loading = true;
      upload(formData)
        .then((res) => {
          if (res) {
            this.$message({
              message: res,
              type: "success",
            });
          }
        })
        .catch((error) => {
          this.$message(error);
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 选择文件后给表单验证的prop字段赋值,并且清除该字段的校验
    handleChange(file, fileList) {
      this.form.fileList = fileList;
      // 防止用户打开了文件选择框之后不选择文件而出现效验失败
      if (this.form.fileList) {
        this.$refs.form.clearValidate("fileList");
      }
    },
    // 删除文件后重新校验该字段
    handleRemove(file, fileList) {
      this.form.fileList = fileList;
      this.$refs.form.validateField("fileList");
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          // 校验成功后执行
          this.uploadFile();
        } else {
          // 失败后执行
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
};
</script>
<style lang="less" scoped>

</style>
